package RabbitMQ.rpc;

import RabbitMQ.Constants.Constants;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class RpcServer {
    public static void main(String[] args) throws IOException, TimeoutException {
//        1.建立连接
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection=connectionFactory.newConnection();
//        2.开启信道
        Channel channel=connection.createChannel();
//        这里使用默认的交换机,不再进行声明
//        声明队列
//        设置消费者的预取数量.一次消费一条消息
        channel.basicQos(1);
//      接收请求
        DefaultConsumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//                在接受到请求之后,就需要进行响应
                String request=new String(body);
                System.out.println("接收到请求:"+request);
//                进行响应
                String response="针对request:"+request+"响应成功";
                AMQP.BasicProperties basicProperties=new AMQP.BasicProperties().builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
//                进行响应
                channel.basicPublish("",Constants.RPC_RESPONSE_QUEUE,basicProperties,response.getBytes(StandardCharsets.UTF_8));
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        channel.basicConsume(Constants.RPC_REQUEST_QUEUE,false,consumer);
        channel.close();
        connection.close();
    }
}